//
//  OtherSearchCityViewController.swift
//  EasePods
//
//  Created by 李然 on 2024/5/18.
//

import UIKit
import Alamofire
import EarbudsCommon

class OtherSearchCityViewController: ViewController {
    
    private var searchArray: [String] = []
    private var isSearch = true
    private var searchText: String = ""
    private var cityProfile = [String: Int]()
    private var cityGPS = [String: [String: Double]]()

    override func makeUI() {
        super.makeUI()
        
        view.addSubview(searchBar)
        view.addSubview(tableView)
        
        searchBar.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(kStatusBarHeight + 10)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(56)
        }

        tableView.snp.makeConstraints { make in
            make.top.equalTo(searchBar.snp.bottom)
            make.leading.trailing.bottom.equalToSuperview()
        }
        clearBackgroundColor()
    }
    
    private func clearBackgroundColor() {
        guard let UISearchBarBackground: AnyClass = NSClassFromString("UISearchBarBackground") else { return }
        for view in searchBar.subviews {
            for subview in view.subviews where subview.isKind(of: UISearchBarBackground) {
                subview.alpha = 0
            }
        }
    }
    
    //根据输入的关键字来过滤搜索结果
    func filterBySubstring(filterStr: String) {
        isSearch = true
        var text = ""
        if let str = filterStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed){
            text = str
        }
        _ = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
        let api = apiSearchCity + "text=\(text)?bkt=fp-US-en-US-def&device=desktop"
        AF.request(api,headers: yahooHeaders).responseJSON { [weak self] response in
            switch response.result {
            case .success(let json):
                self?.cityProfile = [String:Int]()
                self?.searchArray = []
                self?.cityGPS = [String:[String:Double]]()
                if let data = json as? [AnyObject] {
                    log.debug("data =\(data)")
                    if data.count > 0 {
                        for value in data {
                            let woeid = value.value(forKey: "woeid") as? Int
                            let qualifiedName = value.value(forKey: "qualifiedName") as? String
                            let gpsLat = value.value(forKey: "lat") as? Double
                            let gpsLon = value.value(forKey: "lon") as? Double
                            if let name = qualifiedName {
                                self?.searchArray.append(name)
                                if let lat = gpsLat,let lon = gpsLon {
                                    self?.cityGPS[name] = ["lat":lat,"lon":lon]
                                }
                                if woeid != nil {
                                    self?.cityProfile[name] = woeid
                                    
                                }
                            }
                            
                        }
                       self?.tableView.reloadData()
                    }
                }
            case .failure(let error):
                log.debug(error)
            }
        }
    }
    
    private lazy var searchBar: UISearchBar = {
        let searchBar = UISearchBar()
        searchBar.placeholder = "search city"
        searchBar.showsCancelButton = true
        searchBar.delegate = self
        searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
        searchBar.barStyle = .default
        //        tempSearchBar.searchBarStyle = UISearchBarStyle.minimal
        searchBar.isTranslucent = false
        searchBar.backgroundImage = UIImage()
        searchBar.backgroundColor = R.color.common_2_bg_page()
        searchBar.showsScopeBar = true
        if let searchField = searchBar.value(forKey: "searchField") as? UITextField {
            searchField.backgroundColor = R.color.common_10_bg_page()
            searchField.textColor = R.color.common_3_text()
            
            let imageView = UIImageView(image: R.image.ic_common_search())
            imageView.contentMode = .scaleAspectFit
            
            let cView = UIView(frame: CGRect(x: 0, y: 0, width: 36, height: 36))
            cView.snp.makeConstraints { make in
                make.size.equalTo(CGSizeMake(36, 36))
            }
            cView.addSubview(imageView)
            imageView.snp.makeConstraints { make in
                make.center.equalToSuperview()
            }
            
            searchField.leftView = cView
            searchField.leftViewMode = .always
        }
        if let cancelButton = searchBar.value(forKey: "cancelButton") as? UIButton {
            cancelButton.setTitleColor(R.color.common_27_main_color(), for: UIControl.State.normal)
        }
        if let view = searchBar.subviews.first?.subviews.last?.subviews.first {
            view.layer.cornerRadius = 7
            view.backgroundColor = R.color.common_10_bg_page()
        }
        
        if let UISearchBarBackground: AnyClass = NSClassFromString("UISearchBarBackground") {
            for view in searchBar.subviews {
                for subview in view.subviews {
                    if subview.isKind(of: UISearchBarBackground) {
                        subview.alpha = 0
                    }
                }
            }
        }
        
        searchBar.becomeFirstResponder()
        return searchBar
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 44
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        return tableView
    }()

}

extension OtherSearchCityViewController: UISearchBarDelegate {

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        isSearch = false
        searchBar.resignFirstResponder()
        self.dismiss(animated: true, completion: nil)
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        filterBySubstring(filterStr: searchBar.text!)
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        self.searchText = searchText
        filterBySubstring(filterStr: searchText)
    }
}

extension OtherSearchCityViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "cellId"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if cell == nil {
            cell = UITableViewCell.init(style: UITableViewCell.CellStyle.default, reuseIdentifier: identifier)
        }
        cell?.backgroundColor = R.color.common_2_bg_page()

        let row = indexPath.row
        if isSearch {
            if searchArray.count > row {
                var cityName = searchArray[row]
                let isNeed = self.checkIsNeedAddCN(city: cityName)
                if isNeed {
                    cityName = cityName + ", CN"
                }
                cell?.textLabel?.text = cityName
                cell?.textLabel?.textColor = R.color.common_3_text()
                if let label = cell?.textLabel {
                    setLabelColor(label: label, resultStr: cityName, searchStr: searchText)
                }

            }
        } else {
            if searchArray.count > row {
                var cityName = searchArray[row]
                let isNeed = self.checkIsNeedAddCN(city: cityName)
                if isNeed {
                    cityName = cityName + ", CN"
                }
                cell?.textLabel?.text = cityName
                cell?.textLabel?.textColor = R.color.common_3_text()
                if let label = cell?.textLabel {
                    setLabelColor(label: label, resultStr: cityName, searchStr: searchText)
                }

            }
        }

        return cell!
    }

    private func setLabelColor(label: UILabel, resultStr: String, searchStr: String) {
        let attrstring: NSMutableAttributedString = NSMutableAttributedString(string: resultStr)
        let str = NSString(string: resultStr)
        let theRange = str.range(of: searchStr)
        attrstring.addAttribute(NSAttributedString.Key.foregroundColor, value: R.color.common_3_text() ?? .clear, range: theRange)
        label.attributedText = attrstring
    }

    private func checkIsNeedAddCN(city: String) -> Bool {
        if city.hasSuffix("HK") || city.hasSuffix("TW") || city.hasSuffix("MO") {
            return true
        }
        return false
    }
}

extension OtherSearchCityViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        log.debug("didSelectRowAt =\(indexPath.row)")
        let row = indexPath.row
        if searchArray.count > row {
            Weather.shared.cityEN = searchArray[row]
            Weather.shared.openWeatherCity = searchArray[row]
            if let cityGPSInfo = cityGPS[searchArray[row]] {
                if cityGPSInfo["lat"] != nil, cityGPSInfo["lon"] != nil {
                    Weather.shared.cityGPSInfo = cityGPSInfo
                }
            }
        }
        Weather.shared.getOpenWeather()
        searchBar.resignFirstResponder()
        self.dismiss(animated: true, completion: nil)
    }
}
